package com.example.webapp.web.controller;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.example.webapp.hibernate.Contact;
import com.example.webapp.hibernate.HibernateManager;

@Controller
@RequestMapping(value = "contact/")
public class TestController {
	
	private HibernateManager hibernateManager;
	
	@RequestMapping(value = "contactForm.html")
	public String contactForm(Model model) {
		Session session = hibernateManager.createSession();
		session.beginTransaction();
		List<?> result = session.createQuery("from Contact").list();
		
		model.addAttribute("contactList", result);
		return "contact/contactForm";
	}
	
	@RequestMapping(value = "submitContactForm.html", method = RequestMethod.POST)
	public String submitContactForm(@RequestParam String firstName, @RequestParam String lastName, @RequestParam String email, Model model) {
		Session session = hibernateManager.createSession();
		Transaction t = session.beginTransaction();
		
		Contact contact = new Contact();
		contact.setFirstName(firstName);
		contact.setLastName(lastName);
		contact.setEmail(email);
		session.save(contact);
		
		session.flush();
		t.commit();
		session.close();
		
		return "redirect:contactForm.html";
	}
	
	@RequestMapping(value = "deleteContact.html")
	public String deleteContact(@RequestParam Long id, Model model) {
		Session session = hibernateManager.createSession();
		Transaction t = session.beginTransaction();
		
		Object contact = session.load(Contact.class, id);
		session.delete(contact);
		
		session.flush();
		t.commit();
		session.close();
		
		return "redirect:contactForm.html";
	}
	
	@Required
	public void setHibernateManager(HibernateManager hibernateManager) {
		this.hibernateManager = hibernateManager;
	}
}
